// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <nlohmann/json.hpp>
#include <kllm/utility/log.h>

namespace kllm {

    template<typename T>
    static T json_value(const nlohmann::ordered_json &body, const std::string &key, const T &default_value) {
        // Fallback null to default value
        if (body.contains(key) && !body.at(key).is_null()) {
            try {
                return body.at(key);
            } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const &) {
                LOG(WARNING)<<"Wrong type supplied for parameter '"<<key<<"'. Expected '"<< nlohmann::ordered_json(default_value).type_name()<<"', using default value";
                return default_value;
            }
        } else {
            return default_value;
        }
    }
}  // namespace kllm
